package org.gp.core.web;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.gp.core.entity.CheckModel;
import org.gp.core.service.IWechatService;
import org.gp.core.utils.MessageUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


/**
 * Created by luoliang on 2017/1/28.
 */
@RestController
@RequestMapping("/wechat")
@Slf4j
public class WxConnController {
    @Resource
    private IWechatService wechatService;

    @RequestMapping(value = "/check")
    public String check(CheckModel checkModel, HttpServletRequest request, HttpServletResponse response) {
        log.info("checkModel:{}", JSON.toJSONString(checkModel));
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            String echostr = wechatService.checkSignature(checkModel);
            log.info("start check wechat");

            return echostr;
        } else {
            // 进入POST接收消息处理
            log.info("enter post");
            // 接收消息并返回消息
            String message = acceptMessage(request, response);

            return message;
        }
    }

    /**
     * 接收用户消息
     *
     * @param request
     * @param response
     * @return
     */
    public String acceptMessage(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> map = null;

        map = MessageUtil.xmlToMap(request);

        return wechatService.initMessage(map);
    }
}
